package com.system.handler;


import com.common.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 参数校验统一异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.warn("参数校验异常:{}{}", fieldError.getField(),fieldError.getDefaultMessage());
        return R.fail(fieldError.getField()+fieldError.getDefaultMessage());
    }

    /**
     * 参数校验统一异常处理
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R handleException(Exception ex) {
        return R.fail(ex.getCause().getMessage());
    }
}
